package top.lyjwn.todo.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;

import java.util.HashMap;
import java.util.Map;

/**
 * *
 * 封装了XML转换成object，object转换成XML的代码
 *
 * @author Steven
 */
public class XMLUtil {
    /**
     * 将对象直接转换成String类型的 XML输出
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
        try {
            return xmlMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 将String类型的xml转换成对象
     */
    public static <T> T convertXmlStrToObject(Class<T> clazz, String xmlStr) {
        XmlMapper xmlMapper = new XmlMapper();
        try {
            return xmlMapper.readValue(xmlStr, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 将String类型的xml转换成Map
     */
    public static Map<String, String> convertXmlStrToObject(String xmlStr) {
        XmlMapper xmlMapper = new XmlMapper();
        try {
            return xmlMapper.readValue(xmlStr, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


}
